package com.example.sprintboot.controller;

import com.example.sprintboot.common.Result;
import com.example.sprintboot.dto.SendMessage;
import com.example.sprintboot.dto.WeChatAccessTokenResponse;
import com.example.sprintboot.entity.WeChatToken;
import com.example.sprintboot.service.WeChatService;
import com.example.sprintboot.service.WeChatTokenService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

/**
 * 微信API调用控制器
 * 演示如何调用微信第三方API
 */
@RestController
@RequestMapping("/wechat")
@Tag(name = "微信token", description = "微信相关接口")

public class WeChatController {

    @Resource
    private WeChatService weChatService;
    
    @Resource
    private WeChatTokenService weChatTokenService;
    
    @Resource
    private com.example.sprintboot.common.HttpUtil httpUtil;
    
    @Resource
    private com.fasterxml.jackson.databind.ObjectMapper objectMapper;
    
    @Value("${wechat.default.appid}")
    private String defaultAppid;
    
    @Value("${wechat.default.secret}")
    private String defaultSecret;
    

    /**
     * 获取微信 access_token
     * 
     * 测试URL：GET http://localhost:9090/wechat/access-token?appid=YOUR_APPID&secret=YOUR_SECRET
     * 
     * @param appid 微信AppID
     * @param secret 微信AppSecret
     * @return access_token响应
     */
    @Operation(summary = "获取微信access_token", description = "调用微信API获取access_token")
    @GetMapping("/access-token")
    public Result getAccessToken(
            @Parameter(description = "微信AppID", required = false) @RequestParam(defaultValue = "${wechat.default.appid}") String appid,
            @Parameter(description = "微信AppSecret", required = false) @RequestParam(defaultValue = "${wechat.default.secret}") String secret) {
        
        // 调用服务层方法
        WeChatAccessTokenResponse response = weChatService.getAccessToken(appid, secret);
        
        // 判断是否成功
        if (response.isSuccess()) {
            return Result.success(response);
        } else {
            return Result.error("获取access_token失败: " + response.getErrmsg());
        }
    }

    /**
     * 获取微信 access_token（返回原始JSON字符串）
     * 
     * @param appid 微信AppID
     * @param secret 微信AppSecret
     * @return access_token原始JSON字符串
     */
//    @Operation(summary = "获取微信access_token（原始JSON）", description = "返回原始JSON字符串格式的access_token")
//    @GetMapping("/access-token/raw")
//    public Result getAccessTokenRaw(
//            @Parameter(description = "微信AppID", required = false) @RequestParam(defaultValue = "${wechat.default.appid}") String appid,
//            @Parameter(description = "微信AppSecret", required = false) @RequestParam(defaultValue = "${wechat.default.secret}") String secret) {
//
//        String response = weChatService.getAccessTokenAsString(appid, secret);
//        return Result.success(response);
//    }

    /**
     * 智能获取 access_token（推荐使用）
     * 
     * 先从数据库查询有效的token，如果过期才调用微信API
     * 
     * @param appid 微信AppID
     * @param secret 微信AppSecret
     * @return access_token响应
     */
    @Operation(summary = "智能获取微信access_token", description = "先从数据库查询有效token，过期才重新获取")
    @GetMapping("/access-token/smart")
    public Result getAccessTokenSmart(
            @Parameter(description = "微信AppID", required = false) @RequestParam(defaultValue = "${wechat.default.appid}") String appid,
            @Parameter(description = "微信AppSecret", required = false) @RequestParam(defaultValue = "${wechat.default.secret}") String secret) {
        
        WeChatAccessTokenResponse response = weChatService.getAccessTokenSmart(appid, secret);
        
        if (response.isSuccess()) {
            return Result.success(response);
        } else {
            return Result.error("获取access_token失败: " + response.getErrmsg());
        }
    }

    /**
     * 从数据库查询Token信息
     * 
     * @param appid 微信AppID
     * @return Token信息
     */
    @Operation(summary = "查询数据库中的Token", description = "根据AppID查询数据库中存储的Token信息")
    @GetMapping("/token/info")
    public Result getTokenInfo(
            @Parameter(description = "微信AppID", required = false) @RequestParam(defaultValue = "${wechat.default.appid}") String appid) {
        
        WeChatToken token = weChatTokenService.getTokenByAppid(appid);
        
        if (token == null) {
            return Result.error("未找到该AppID的Token记录");
        }
        
        return Result.success(token);
    }

    /**
     * 查询有效的Token（未过期）
     * 
     * @param appid 微信AppID
     * @return 有效的Token信息
     */
    @Operation(summary = "查询有效的Token", description = "查询数据库中未过期的Token")
    @GetMapping("/token/valid")
    public Result getValidToken(
            @Parameter(description = "微信AppID", required = false) @RequestParam(defaultValue = "${wechat.default.appid}") String appid) {
        
        WeChatToken token = weChatTokenService.getValidToken(appid);
        
        if (token == null) {
            return Result.error("未找到有效的Token，可能需要重新获取");
        }
        
        return Result.success(token);
    }

    /**
     *
     * @param templateId 模板id
     */
    @Operation(summary = "发布消息订阅", description = "")
    @GetMapping("/sendMessage/{templateId}")
    public Result sendMessage(@PathVariable String templateId) {
        SendMessage result = weChatService.sendMessage(templateId);
        return Result.success(result);
    }
    
    /**
     * 使用实际模板ID发送订阅消息（推荐测试）
     */
    @Operation(summary = "发送实际模板订阅消息", description = "使用你的真实模板ID发送订阅消息")
    @GetMapping("/sendRealMessage")
    public Result sendRealMessage() {
        SendMessage result = weChatService.sendRealTemplateMessage();
        return Result.success(result);
    }
    
    /**
     * 发送课程预约通知
     */
    @Operation(summary = "发送课程预约通知", description = "发送课程预约成功的订阅消息")
    @GetMapping("/sendCourseNotification")
    public Result sendCourseNotification(
            @Parameter(description = "用户名称") @RequestParam(defaultValue = "测试学员") String userName,
            @Parameter(description = "课程名称") @RequestParam(defaultValue = "Spring Boot实战课程") String courseName,
            @Parameter(description = "课程时间") @RequestParam(required = false) String courseTime,
            @Parameter(description = "讲师名称") @RequestParam(defaultValue = "专业讲师") String teacherName,
            @Parameter(description = "温馨提示") @RequestParam(defaultValue = "请按时参加课程学习，如有疑问请联系客服") String tips) {
        
        SendMessage result = weChatService.sendCourseBookingNotification(
            userName, courseName, courseTime, teacherName, tips
        );
        return Result.success(result);
    }
    
    /**
     * 测试不同的小程序状态
     */
    @Operation(summary = "测试不同小程序状态", description = "测试developer/trial/formal状态")
    @GetMapping("/testStates")
    public Result testDifferentStates() {
        String templateId = "zvaRsziQ2U139jQdNUSSX8cCgyqHe_r5xIsuGo36wR8";
        
        // 测试三种状态
        SendMessage developerResult = weChatService.sendMessageWithState(templateId, "developer");
        SendMessage trialResult = weChatService.sendMessageWithState(templateId, "trial");
        SendMessage formalResult = weChatService.sendMessageWithState(templateId, "formal");
        
        java.util.Map<String, Object> results = new java.util.HashMap<>();
        results.put("developer", developerResult);
        results.put("trial", trialResult);
        results.put("formal", formalResult);
        
        return Result.success(results);
    }
    
    /**
     * 发送最简单的测试消息
     */
    @Operation(summary = "发送最简单测试消息", description = "只包含必要字段的测试")
    @GetMapping("/sendSimpleTest")
    public Result sendSimpleTest() {
        String templateId = "zvaRsziQ2U139jQdNUSSX8cCgyqHe_r5xIsuGo36wR8";
        SendMessage result = weChatService.sendSimpleMessage(templateId);
        return Result.success(result);
    }
    
    /**
     * 发送最小化请求（排除可选字段）
     */
    @Operation(summary = "最小化请求测试", description = "只包含必填字段，排除可选字段")
    @GetMapping("/sendMinimal")
    public Result sendMinimalMessage() {
        SendMessage result = weChatService.sendMinimalMessage();
        return Result.success(result);
    }
    
    /**
     * 测试多用户发送
     */
    @Operation(summary = "多用户测试", description = "测试发送给不同用户")
    @GetMapping("/testUsers")
    public Result testDifferentUsers() {
        SendMessage result = weChatService.testDifferentUsers();
        return Result.success(result);
    }
    
    /**
     * 诊断订阅消息问题
     */
    @Operation(summary = "诊断订阅消息问题", description = "分析412错误的可能原因和解决方案")
    @GetMapping("/diagnose")
    public Result diagnoseSubscriptionMessage() {
        java.util.Map<String, Object> diagnosis = weChatService.diagnoseSubscriptionMessage();
        return Result.success(diagnosis);
    }
    
    /**
     * 获取测试代码示例
     */
    @Operation(summary = "获取测试代码", description = "获取小程序订阅消息测试代码")
    @GetMapping("/getTestCode")
    public Result generateTestCode() {
        java.util.Map<String, Object> codeExamples = weChatService.generateTestCode();
        return Result.success(codeExamples);
    }
    
    /**
     * 测试不同的字段组合
     */
    @Operation(summary = "测试不同字段组合", description = "尝试不同的模板字段组合找出正确格式")
    @GetMapping("/testFields")
    public Result testDifferentFieldCombinations() {
        java.util.Map<String, Object> results = weChatService.testDifferentFieldCombinations();
        return Result.success(results);
    }
    
    /**
     * 验证AppID和模板配置
     */
    @Operation(summary = "验证配置", description = "验证AppID和模板ID的匹配性")
    @GetMapping("/validate")
    public Result validateAppIdAndTemplate() {
        java.util.Map<String, Object> validation = weChatService.validateAppIdAndTemplate();
        return Result.success(validation);
    }
    
    /**
     * 发送到测试号
     */
    @Operation(summary = "测试号发送", description = "尝试发送到微信测试号")
    @GetMapping("/sendToTest")
    public Result sendToTestAccount() {
        SendMessage result = weChatService.sendToTestAccount();
        return Result.success(result);
    }
    
    /**
     * 验证AppID匹配性
     */
    @Operation(summary = "验证AppID匹配", description = "基于模板信息确认的AppID匹配性验证")
    @GetMapping("/verifyAppId")
    public Result verifyAppIdMatch() {
        java.util.Map<String, Object> verification = weChatService.verifyAppIdMatch();
        return Result.success(verification);
    }
    
    /**
     * 使用确认的模板格式发送
     */
    @Operation(summary = "确认模板格式发送", description = "使用基于截图确认的模板字段格式发送消息")
    @GetMapping("/sendConfirmed")
    public Result sendWithConfirmedTemplate() {
        SendMessage result = weChatService.sendWithConfirmedTemplate();
        return Result.success(result);
    }
    
    /**
     * 立即发送测试（用于订阅后立即调用）
     */
    @Operation(summary = "立即发送测试", description = "订阅后立即发送，测试时效性")
    @GetMapping("/sendImmediate")
    public Result sendImmediate() {
        SendMessage result = weChatService.sendWithConfirmedTemplate();
        return Result.success(result);
    }
    
    /**
     * 详细调试412错误
     */
    @Operation(summary = "调试412错误", description = "详细分析412 PRECONDITION_FAILED错误原因")
    @GetMapping("/debug412")
    public Result debug412Error() {
        SendMessage result = weChatService.debugSubscriptionMessage();
        return Result.success(result);
    }

    /**
     * 全面诊断412错误
     */
    @Operation(summary = "全面诊断412错误", description = "提供详细的412错误分析和解决方案")
    @GetMapping("/diagnose412")
    public Result diagnose412Error() {
        return Result.success(weChatService.diagnose412Error());
    }

    /**
     * 针对当前问题的精准诊断
     */
    @Operation(summary = "当前问题诊断", description = "基于日志分析的精准问题诊断")
    @GetMapping("/diagnoseCurrent")
    public Result diagnoseCurrentIssue() {
        return Result.success(weChatService.diagnoseCurrentIssue());
    }

    /**
     * 修复后的测试发送接口
     */
    @Operation(summary = "修复后的测试发送", description = "使用修复后的逻辑测试发送订阅消息")
    @GetMapping("/testFixed")
    public Result testFixedSend() {
        SendMessage result = weChatService.sendWithConfirmedTemplate();
        
        // 根据实际结果返回正确的状态
        if (result.getData() != null && result.getData().toString().contains("✅")) {
            return Result.success(result, "发送成功");
        } else {
            return Result.error(result.getData() != null ? result.getData().toString() : "发送失败");
        }
    }

    /**
     * 测试订阅消息完整流程
     */
    @Operation(summary = "测试订阅消息流程", description = "提供完整的订阅消息测试流程指导")
    @GetMapping("/testFlow")
    public Result testSubscriptionFlow() {
        return Result.success(weChatService.testSubscriptionFlow());
    }

    /**
     * 通过微信登录code获取OpenID
     */
    @Operation(summary = "获取用户OpenID", description = "通过微信登录code获取用户OpenID")
    @PostMapping("/getOpenId")
    public Result getOpenId(@RequestBody java.util.Map<String, String> request) {
        String code = request.get("code");
        if (code == null || code.trim().isEmpty()) {
            return Result.error("登录凭证不能为空");
        }
        
        try {
            // 调用微信API获取session_key和openid
            java.util.Map<String, Object> params = new java.util.HashMap<>();
            params.put("appid", defaultAppid);
            params.put("secret", defaultSecret);
            params.put("js_code", code);
            params.put("grant_type", "authorization_code");
            
            // 使用HttpUtil发送请求
            com.example.sprintboot.common.HttpUtil.HttpResult<String> result = httpUtil.get(
                "https://api.weixin.qq.com/sns/jscode2session", 
                params, 
                String.class
            );
            
            if (result.isSuccess()) {
                // 解析响应
                @SuppressWarnings("unchecked")
                java.util.Map<String, Object> responseData = objectMapper.readValue(
                    result.getRawResponse(), 
                    java.util.Map.class
                );
                
                if (responseData.containsKey("openid")) {
                    java.util.Map<String, Object> data = new java.util.HashMap<>();
                    data.put("openid", responseData.get("openid"));
                    data.put("session_key", responseData.get("session_key"));
                    return Result.success(data);
                } else {
                    return Result.error("获取OpenID失败: " + responseData.get("errmsg"));
                }
            } else {
                return Result.error("调用微信API失败: " + result.getErrorMessage());
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取OpenID异常: " + e.getMessage());
        }
    }
}

